package com.cpi.cornpp.purchase.program.services;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.purchase.program.converter.PurchaseOrderChargeConverter;
import com.cpi.cornpp.purchase.program.dao.PurchaseOrderChargeDAO;
import com.cpi.cornpp.purchase.program.dto.PurchaseOrderChargeDTO;
import com.cpi.cornpp.purchase.program.exception.PurchaseProgramException;
import com.cpi.cornpp.purchase.program.view.PurchaseOrderChargeView;

public class PurchaseOrderChargeService {
	private static final String ERROR_CHARGE_EXISTS = "error.message.purchaseprogram.purchaseorder.charge.exists";
	public void insert(PurchaseOrderChargeView purchaseOrderChargeView)throws PurchaseProgramException{
		PurchaseOrderChargeDAO purchaseOrderChargeDAO = null;
		PurchaseOrderChargeDTO purchaseOrderChargeDTO = null;
		try{
			purchaseOrderChargeDAO = new PurchaseOrderChargeDAO();
			purchaseOrderChargeDTO = PurchaseOrderChargeConverter.convert(purchaseOrderChargeView);
			if( !purchaseOrderChargeDAO.existsCharge(purchaseOrderChargeDTO) ){
				purchaseOrderChargeDAO.insertPurchaseOrderCharge(purchaseOrderChargeDTO);
			}else{
				throw new PurchaseProgramException(ERROR_CHARGE_EXISTS, CornPPException.LAYER_SERVICE,CornPPException.ACTION_INSERT);
			}
		} catch (PurchaseProgramException purchaseProgramException) {
			throw purchaseProgramException;
		}catch (Exception exception){
			PurchaseProgramException purchaseProgramException = null;
			exception.printStackTrace(System.err);
			purchaseProgramException = new PurchaseProgramException(exception , CornPPException.LAYER_SERVICE,CornPPException.ACTION_INSERT);
			throw purchaseProgramException;
		}
	}
	
	public void delete(PurchaseOrderChargeView purchaseOrderChargeView)throws PurchaseProgramException{
		PurchaseOrderChargeDAO purchaseOrderChargeDAO = null;
		PurchaseOrderChargeDTO purchaseOrderChargeDTO = null;
		try{
			purchaseOrderChargeDAO = new PurchaseOrderChargeDAO();
			purchaseOrderChargeDTO = PurchaseOrderChargeConverter.convert(purchaseOrderChargeView);
			purchaseOrderChargeDAO.delete(purchaseOrderChargeDTO);
		} catch (PurchaseProgramException purchaseProgramException) {
			purchaseProgramException.printStackTrace(System.err);
			purchaseProgramException= new PurchaseProgramException(purchaseProgramException, CornPPException.LAYER_SERVICE,CornPPException.ACTION_DELETE);
			throw purchaseProgramException;
		}catch (Exception exception){
			PurchaseProgramException purchaseProgramException = null;
			exception.printStackTrace(System.err);
			purchaseProgramException = new PurchaseProgramException(exception , CornPPException.LAYER_SERVICE,CornPPException.ACTION_DELETE);
			throw purchaseProgramException;
		}
	}
}